package auth

import (
	"arc_srv4/common"
	"github.com/dgrijalva/jwt-go"
	jailer "github.com/iris-contrib/middleware/jwt"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/context"
)

/**
 * 验证 jwt
 * @method JwtHandler
 */
func JwtHandler() *jailer.Middleware {
	if common.AppConCfg.Authorization == 1 {
		return jailer.New(jailer.Config{

			// 错误处理函数
			ErrorHandler: func(ctx context.Context, err error) {
				if err == nil {
					return
				}
				ctx.StopExecution()
				ctx.StatusCode(iris.StatusUnauthorized)

				_, _ = ctx.JSON(common.ApiRspOnly{Code: common.Http10008, Message: common.Http10008Desc})
			},

			// 从参数里提取token
			Extractor: jailer.FromParameter("token"),

			ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
				return []byte(common.JwtCfg.Secret), nil
			},

			SigningMethod: jwt.SigningMethodHS256,
		})
	} else {
		return jailer.New(jailer.Config{

			// 错误处理函数
			ErrorHandler: func(ctx context.Context, err error) {
				if err == nil {
					return
				}
				ctx.StopExecution()
				ctx.StatusCode(iris.StatusUnauthorized)

				_, _ = ctx.JSON(common.ApiRspOnly{Code: common.Http10008, Message: common.Http10008Desc})
			},
			// 从请求头的Authorization字段中提取，这个是默认值
			Extractor: jailer.FromAuthHeader,

			ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
				return []byte(common.JwtCfg.Secret), nil
			},

			SigningMethod: jwt.SigningMethodHS256,
		})
	}
}
